package com.example.androidmvvmdemo.viewModel;

import android.graphics.BitmapFactory;

import com.example.androidmvvmdemo.model.ImageModel;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ImageOperationVM {

    private static ImageModel imageModel;

    public static ImageModel getImageModel() {
        if (imageModel == null) {
            imageModel = new ImageModel();
        }
        return imageModel;
    }

    public static void download(String url) {
        if (imageModel == null) {
            imageModel = new ImageModel();
        }
        imageModel.setUrl(url);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(imageModel.getUrl());
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setConnectTimeout(5000);
                    httpURLConnection.setRequestMethod("GET");
                    if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        InputStream inputStream = httpURLConnection.getInputStream();
                        imageModel.setBitmap(BitmapFactory.decodeStream(inputStream));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
